import { ChartComponent } from '/src/components/component/chart/chartcomponent.js'
import { ComponentManager } from '/src/components/component/componentManager.js'

let currentColumns = 32;
let currentRows = 32;
let boxCounter = 0;
let cellWidth = 0;
let cellHeight = 0;
let isNeedToolbox = false;
let isPreventDragging = false;
let isNeedTitle = true;

export function generateGrid(columns, rows) {
    const container = $('#gridContainer');
    container.empty().css({
        'grid-template-columns': `repeat(${columns}, 1fr)`,
        'grid-template-rows': `repeat(${rows}, 1fr)`
    });

    const totalItems = columns * rows;
    for (let i = 1; i <= totalItems; i++) {
        $('<div>', {
            'class': 'grid-item',
            'data-index': i,
            'data-row': Math.ceil(i / columns),
            'data-col': ((i - 1) % columns) + 1,
            // 'text': i
        }).appendTo(container);
    }

    currentColumns = columns;
    currentRows = rows;
    calculateCellSize(); // 生成后立即计算尺寸
}

export function calculateCellSize() {
    const container = $('#gridContainer');
    const containerWidth = container.innerWidth();
    const containerHeight = container.innerHeight();

    cellWidth = ((containerWidth - (currentColumns - 1)) / currentColumns);
    cellHeight = ((containerHeight - (currentRows - 1)) / currentRows);

    // console.log(`单元格尺寸: ${cellWidth} × ${cellHeight}`); // 可选调试
}

export function pixelToGrid(x, y) {
    // Math.max(1, ...) 确保最小值为1, Math.min 确保不超过范围
    const col = Math.max(1, Math.min(currentColumns, Math.floor(x / (cellWidth + 1)) + 1));
    const row = Math.max(1, Math.min(currentRows, Math.floor(y / (cellHeight + 1)) + 1));
    return { col, row };
}

export function gridToPixel(col, row) {
    // col和row从1开始，所以要减1
    const x = (col - 1) * (cellWidth + 1);
    const y = (row - 1) * (cellHeight + 1);
    return { x, y };
}

export function gridSizeToPixel(cols, rows) {
    // 计算尺寸时也使用缓存的整数 cellWidth/Height
    const width = cols * cellWidth + (cols - 1);
    const height = rows * cellHeight + (rows - 1);
    return { width, height };
}

export function createGridBox(startCol = 1, startRow = 1, widthCols = 4, heightRows = 3, name, searchbar) {
    boxCounter++;
    const boxId = `gridBox_${boxCounter}`;
    const position = gridToPixel(startCol, startRow);
    const size = gridSizeToPixel(widthCols, heightRows);

    const chartContainerWidth = size.width - 20;
    const chartContainerHeight = size.height - 20;

    // 使用 jQuery 创建元素，更简洁
    const $box = $(`
        <div class="grid-box" id="${boxId}">
            <div class="box-header"></div>
            <span class="close-btn" title="关闭">×</span>
            <div class="box-content">
                <div id="${name}" style="width:${chartContainerWidth}px; height:${chartContainerHeight}px;"></div>
            </div>
            <div class="resize-handle" title="调整大小"></div>
        </div>`).css({
        left: position.x,
        top: position.y,
        width: size.width,
        height: size.height
    }).appendTo('#gridContainer'); // 直接追加

    // 设置 data 属性
    $box.attr({
        'data-start-col': startCol,
        'data-start-row': startRow,
        'data-width-cols': widthCols,
        'data-height-rows': heightRows,
        'data-searchbar': searchbar
    });

    makeGridBoxDraggable($box);
    makeGridBoxResizable($box, name);

    $box.disableDraggable(isPreventDragging);

    return $box;
}

// 使网格框可拖拽
export function makeGridBoxDraggable(box) {
    const $container = $('#gridContainer');
    const borderWidth = 0; // 从 CSS 中获取或硬编码，这里硬编码为 2px

    // 计算精确的 containment 边界，考虑容器偏移和框的边框
    const getContainment = () => {
        const containerOffset = $container.offset();
        const containerWidth = $container.innerWidth();
        const containerHeight = $container.innerHeight();
        return [
            containerOffset.left + borderWidth,        // x1: 左边界
            containerOffset.top + borderWidth,         // y1: 上边界
            containerOffset.left + containerWidth - borderWidth, // x2: 右边界
            containerOffset.top + containerHeight - borderWidth  // y2: 下边界
        ];
    };

    box.draggable({
        handle: '.box-header',
        // containment: '#gridContainer', // 旧的 containment，不够精确
        containment: getContainment(), // 使用动态计算的精确边界
        scroll: false,
        grid: [cellWidth + 1, cellHeight + 1], // 使用缓存的整数步长
        start: function () {
            // 拖动开始时也可能需要更新 containment (例如窗口大小刚变过)
            $(this).draggable('option', 'containment', getContainment());
        },
        drag: function (event, ui) {
            const $container = $('#gridContainer');
            const containerOffset = $container.offset();
            const relativeLeft = ui.position.left - containerOffset.left;
            const relativeTop = ui.position.top - containerOffset.top;

            const rawCol = relativeLeft / (cellWidth + 1) + 1;
            const rawRow = relativeTop / (cellHeight + 1) + 1;

            const snappedCol = Math.max(1, Math.min(currentColumns, Math.round(rawCol)));
            const snappedRow = Math.max(1, Math.min(currentRows, Math.round(rawRow)));

            const snappedX = (snappedCol - 1) * (cellWidth + 1);
            const snappedY = (snappedRow - 1) * (cellHeight + 1);

            ui.position.left = containerOffset.left + snappedX;
            ui.position.top = containerOffset.top + snappedY;

            $(this).attr({
                'data-start-col': snappedCol,
                'data-start-row': snappedRow
            });
        },
        stop: function (event, ui) {
            // const containerOffset = $('#gridContainer').offset();
            // const relativeLeft = ui.position.left - containerOffset.left;
            // const relativeTop = ui.position.top - containerOffset.top;
            // const gridPos = pixelToGrid(relativeLeft, relativeTop);
            // showStatus(`框已移动到: 第${gridPos.row}行, 第${gridPos.col}列`);
        }
    });

    box.disableDraggable = function (disable) {
        if (disable) {
            $(this).draggable('disable');
            $(this).find('.box-header').hide();
            $(this).find('.close-btn').hide();
            $(this).find('.resize-handle').hide();
        } else {
            $(this).draggable('enable');
            $(this).find('.box-header').show();
            $(this).find('.close-btn').show();
            $(this).find('.resize-handle').show();
        }
    };
}

// 使网格框可调整大小
export function makeGridBoxResizable(box, name) {
    box.resizable({
        handles: { se: '.resize-handle' },
        containment: '#gridContainer', // resizable 的 containment 通常够用
        grid: [cellWidth + 1, cellHeight + 1], // 使用缓存的整数步长
        minHeight: cellHeight + 1, // 最小尺寸为一个格子
        minWidth: cellWidth + 1,
        resize: function (event, ui) {
            const rawCols = ui.size.width / (cellWidth + 1);
            const rawRows = ui.size.height / (cellHeight + 1);

            const snappedCols = Math.max(1, Math.round(rawCols));
            const snappedRows = Math.max(1, Math.round(rawRows));

            const snappedWidth = snappedCols * cellWidth + (snappedCols - 1);
            const snappedHeight = snappedRows * cellHeight + (snappedRows - 1);

            $(this).css({
                width: snappedWidth,
                height: snappedHeight
            });

            $(this).attr({
                'data-width-cols': snappedCols,
                'data-height-rows': snappedRows
            });

            // isNeedToolbox ? 36 :
            const newHeaderHeight = 0;
            const $chartContainer = $(`#${name}`);
            const chartWidth = snappedWidth;
            const chartHeight = Math.max(0, snappedHeight - newHeaderHeight);

            $chartContainer.css({
                width: chartWidth,
                height: chartHeight
            });

            $(this).attr({
                'data-chart-width': chartWidth,
                'data-chart-height': chartHeight
            });

            if (ComponentManager.get(name)) {

            } else {
                const chartComponent = ChartComponent.getInstance(name);
                if (chartComponent) {
                    chartComponent.resize();
                }
            }
        },
        stop: function (event, ui) {
            const rawCols = ui.size.width / (cellWidth + 1);
            const rawRows = ui.size.height / (cellHeight + 1);
            const snappedCols = Math.max(1, Math.round(rawCols));
            const snappedRows = Math.max(1, Math.round(rawRows));

            const finalWidth = snappedCols * cellWidth + (snappedCols - 1);
            const finalHeight = snappedRows * cellHeight + (snappedRows - 1);

            $(this).css({ width: finalWidth, height: finalHeight });
        }
    });
}

export function adjustGridContainerSize() {
    const $gridContainer = $('#gridContainer');
    const windowWidth = $(window).width();
    const windowHeight = $(window).height();
    const newWidth = windowWidth;
    const newHeight = windowHeight;

    $gridContainer.css({
        'width': `${newWidth}px`,
        'height': `${newHeight}px`
    });

    // 重新计算单元格大小，因为容器尺寸变了
    calculateCellSize();
}

export function loadEchartsDataWithComponent(chartId, sourceData, searchBarComponent) {
    // 如果已有实例，先销毁
    const chartComponent = ChartComponent.getInstance(chartId);
    if (chartComponent) {
        chartComponent.destroy();
    }

    // 创建新的 chartComponent 实例
    var temp = new ChartComponent($('#' + chartId), {
        showToolbox: isNeedToolbox,
        isTitle: isNeedTitle,
        name: chartId,
        chartType: sourceData.chartType,
        dataSource: sourceData.dataSource,
        time: sourceData.time,
        searchBarComponent: searchBarComponent, // 传入搜索栏组件
        sourceData: sourceData, // 传入原始请求参数
    });
    // 开始加载数据
    temp.loadData(sourceData);
}

export function setIsNeedToolbox(value) {
    isNeedToolbox = value
}

export function getIsNeedToolbox() {
    return isNeedToolbox;
}

export function setIsNeedTitle(value) {
    isNeedTitle = value
}

export function getIsNeedTitle() {
    return isNeedTitle;
}

export function setIsPreventDragging(value) {
    isPreventDragging = value;
}

export function getIsPreventDragging() {
    return isPreventDragging;
}